package com.zrrd.network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * @author WanJl
 * @version 1.0
 * @title ReceiveDemo02
 * @description 组播接收
 * @create 2023/10/22 10:40
 */
public class ReceiveDemo02 {
    /**
     *
     * @param multicastHost 组播地址
     * @param port 当前主机监听端口，从哪一个端口接收数据
     * @throws IOException
     */
    public static void receive(String multicastHost,int port) throws IOException {
        //1、创建接收端Socket对象(MulticastSocket)
        MulticastSocket ms=new MulticastSocket(port);
        //2、创建一个箱子,用于接收数据
        DatagramPacket dp=new DatagramPacket(new byte[1024],1024);
        //3、把当前计算机绑定一个组播地址
        ms.joinGroup(InetAddress.getByName(multicastHost));
        //4、将数据接收到箱子中
        ms.receive(dp);
        //5、解析数据包,并打印数据
        String s = new String(dp.getData(), 0, dp.getLength());
        System.out.println("接收到组播数据："+s);
        //6、释放资源
        ms.close();
    }

    public static void main(String[] args) throws IOException {
        receive("224.0.0.0",10010);
    }
}
